import Image from '@/components/common/image'
import Link from '@/components/common/link'
import { MyTabs, MyTabsContent, MyTabsList, MyTabsListTrigger } from '@/components/form/my-tabs'
import CardList, { Card } from '@/components/layout/card-list'
import { getModelsUrl } from '@/utils/build-url/models'
import React from 'react'

export interface ICategoryProps {
  name: string
  slug: string
  children?: ICategoryProps[]
  details?: {
    slug: string
    name: string
  }[]
}

interface Props {
  list: ICategoryProps[]
  // 新增层级参数，控制嵌套样式（可选，默认1级）
  level?: number
}

// 递归组件：处理单层级分类（支持嵌套）
const CategoryTab = ({ item, level = 1 }: { item: ICategoryProps; level?: number }) => {
  // 判断当前分类是否有子分类
  const hasChildren = Array.isArray(item.children) && item.children.length > 0

  return (
    <MyTabs activeValue={item.children?.[0]?.slug || item.slug} className={`mt-${level > 1 ? 4 : 0}`}>
      {/* 嵌套Tab触发区：层级越深，样式越紧凑（可选优化） */}
      <MyTabsList className={`gap-${level > 1 ? 2 : 3}`}>
        {/* 子分类触发按钮 */}
        {hasChildren && item.children?.map((child) => (
          <MyTabsListTrigger key={child.slug} value={child.slug}>
            {child.name}
          </MyTabsListTrigger>
        ))}
      </MyTabsList>

      {/* 内容区：先渲染当前分类的detail（若有） */}
      <MyTabsContent key={`${item.slug}-self`} value={item.slug}>
        <div className='flex flex-wrap gap-content-gap-x md:gap-content-gap-md'>
          {item.details?.map((detail) => (
            <Card key={detail.slug} className='border border-border'>
              <Link className="flex flex-col items-center justify-center p-card-gap-x md:p-card-gap-y" href={getModelsUrl({ language: 'zh', brandSlug: detail.slug })}>
                <div>{detail.name}</div>
              </Link>
            </Card>
          ))}
        </div>
      </MyTabsContent>

      {/* 递归渲染子分类的Tab内容 */}
      {hasChildren && item.children?.map((child) => (
        <MyTabsContent key={child.slug} value={child.slug}>
          <CategoryTab item={child} level={level + 1} />
        </MyTabsContent>
      ))}
    </MyTabs>
  )
}

const CarCategory = ({ list, level = 1 }: Props) => {
  return (
    <div className="w-full">
      <MyTabs activeValue={list[0]?.slug || ''}>
        {/* 顶级Tab触发区 */}
        <MyTabsList className="gap-3 mb-6">
          {list.map((item) => (
            <MyTabsListTrigger key={item.slug} value={item.slug}>
              {item.name}
            </MyTabsListTrigger>
          ))}
        </MyTabsList>

        {/* 顶级Tab内容区：递归渲染子分类 */}
        {list.map((item) => (
          <MyTabsContent key={item.slug} value={item.slug}>
            <CategoryTab item={item} level={level + 1} />
          </MyTabsContent>
        ))}
      </MyTabs>
    </div>
  )
}

export default CarCategory